using System;
using System.Net;
using CloudStorage.API.Exceptions;
using CloudStorage.Properties;

namespace CloudStorage.API.Messages.Extensions
{
	/// <summary>
	/// Extensions on <see cref="IQueueStorageAccount"/>
	/// </summary>
	public static class IMessageQueueDataContextExtensions
	{
		/// <summary>
		/// Checks to see if a named queue exists.
		/// </summary>
		/// <param name="messageQueueDataContext">Queue to check for existance.</param>
		/// <param name="queueName">Name of the queue to find.</param>
		/// <returns>True if the given queue exists</returns>
		/// <exception cref="ArgumentNullException">Expects a non-null, non-empty queueName</exception>
		/// <exception cref="CloudStorageException">If the result returned contains more than one queue that matches the prefix that is the queueName.</exception>
		public static bool QueueExists(this IMessageQueueDataContext messageQueueDataContext, string queueName)
		{
			if (string.IsNullOrEmpty(queueName))
			{
				throw new ArgumentNullException("queueName", Strings.MissingQueueName);
			}

			// I don't care much for this implementation since it uses throw logic. It works but ut is not pretty!
			try
			{
				var queueMetadata = messageQueueDataContext.GetQueueMetadata();
				return queueMetadata != null;
			}
			catch (CloudStorageException cse)
			{
				if (cse.HttpStatusCode == HttpStatusCode.NoContent)
				{
					return false;
				}
				throw;
			}
		}
	}
}